package com.agent.platform.controller;

import com.agent.platform.dto.SessionStatusResponse;
import com.agent.platform.dto.StartSessionRequest;
import com.agent.platform.dto.StopSessionRequest;
import com.agent.platform.entity.Agent;
import com.agent.platform.entity.AgentSession;
import com.agent.platform.service.AgentService;
import com.agent.platform.service.AgentSessionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务API控制器 - 端口3000
 * 对应Node.js版本的业务API
 */
@Tag(name = "业务API", description = "Agent会话管理和运营接口 (端口3000)")
@Slf4j
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class BusinessApiController {

    private final AgentService agentService;
    private final AgentSessionService sessionService;

    /**
     * 启动Agent会话
     * POST /api/agents/:agentId/sessions/:sessionId/start
     */
    @Operation(
        summary = "启动Agent会话",
        description = "启动一个新的Agent会话或恢复暂停的会话，会话将开始持续运行直到被停止",
        responses = {
            @ApiResponse(responseCode = "200", description = "会话启动成功"),
            @ApiResponse(responseCode = "404", description = "Agent不存在"),
            @ApiResponse(responseCode = "400", description = "请求参数错误")
        }
    )
    @PostMapping("/agents/{agentId}/sessions/{sessionId}/start")
    public ResponseEntity<Map<String, Object>> startSession(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId,
        @Parameter(description = "Session ID", required = true) @PathVariable String sessionId,
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "会话启动参数",
            content = @Content(schema = @Schema(implementation = StartSessionRequest.class))
        )
        @RequestBody(required = false) StartSessionRequest request
    ) {
        log.info("Starting session: {} for agent: {}", sessionId, agentId);

        AgentSession session = sessionService.startSession(
            agentId,
            sessionId,
            request != null ? request.getMetadata() : null
        );

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("sessionId", session.getSessionId());
        response.put("agentId", session.getAgentId());
        response.put("status", session.getStatus());

        return ResponseEntity.ok(response);
    }

    /**
     * 停止Agent会话
     * POST /api/agents/:agentId/sessions/:sessionId/stop
     */
    @Operation(
        summary = "停止Agent会话",
        description = "停止正在运行的Agent会话，返回会话执行摘要统计",
        responses = {
            @ApiResponse(responseCode = "200", description = "会话停止成功"),
            @ApiResponse(responseCode = "404", description = "会话不存在"),
            @ApiResponse(responseCode = "400", description = "会话未运行")
        }
    )
    @PostMapping("/agents/{agentId}/sessions/{sessionId}/stop")
    public ResponseEntity<Map<String, Object>> stopSession(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId,
        @Parameter(description = "Session ID", required = true) @PathVariable String sessionId,
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "停止原因",
            content = @Content(schema = @Schema(implementation = StopSessionRequest.class))
        )
        @RequestBody(required = false) StopSessionRequest request
    ) {
        log.info("Stopping session: {} for agent: {}", sessionId, agentId);

        String reason = request != null ? request.getReason() : "Manual stop";
        AgentSession session = sessionService.stopSession(agentId, sessionId, reason);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("sessionId", session.getSessionId());
        response.put("status", session.getStatus());
        response.put("summary", Map.of(
            "stepCount", session.getStepCount(),
            "totalTokens", session.getTotalTokens(),
            "totalCost", session.getTotalCost()
        ));

        return ResponseEntity.ok(response);
    }

    /**
     * 获取会话状态
     * GET /api/agents/:agentId/sessions/:sessionId/status
     */
    @Operation(
        summary = "获取会话状态",
        description = "获取Agent会话的当前状态，包括运行状态、步骤数、Token使用量、成本等信息",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取会话状态"),
            @ApiResponse(responseCode = "404", description = "会话不存在")
        }
    )
    @GetMapping("/agents/{agentId}/sessions/{sessionId}/status")
    public ResponseEntity<SessionStatusResponse> getSessionStatus(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId,
        @Parameter(description = "Session ID", required = true) @PathVariable String sessionId
    ) {
        SessionStatusResponse status = sessionService.getSessionStatus(agentId, sessionId);
        return ResponseEntity.ok(status);
    }

    /**
     * 列出Agent的所有会话
     * GET /api/agents/:agentId/sessions
     */
    @Operation(
        summary = "列出Agent的所有会话",
        description = "获取指定Agent的所有会话列表",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取会话列表"),
            @ApiResponse(responseCode = "404", description = "Agent不存在")
        }
    )
    @GetMapping("/agents/{agentId}/sessions")
    public ResponseEntity<List<AgentSession>> listSessions(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId
    ) {
        List<AgentSession> sessions = sessionService.listSessions(agentId);
        return ResponseEntity.ok(sessions);
    }

    /**
     * 更新Agent控制配置
     * PUT /api/agents/:agentId/control-config
     */
    @Operation(
        summary = "更新Agent控制配置",
        description = "动态更新Agent的控制配置参数，如最大步骤数、超时时间、成本限制等",
        responses = {
            @ApiResponse(responseCode = "200", description = "配置更新成功"),
            @ApiResponse(responseCode = "404", description = "Agent不存在"),
            @ApiResponse(responseCode = "400", description = "配置参数无效")
        }
    )
    @PutMapping("/agents/{agentId}/control-config")
    public ResponseEntity<Map<String, Object>> updateControlConfig(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId,
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "控制配置更新请求",
            content = @Content(schema = @Schema(example = """
                {
                  "propertyMap": {
                    "maxSteps": 20,
                    "maxFailures": 3,
                    "maxExecutionTime": 300000
                  },
                  "updatedBy": "admin",
                  "reason": "增加处理限制",
                  "effectiveImmediately": true
                }
                """))
        )
        @RequestBody Map<String, Object> request
    ) {
        @SuppressWarnings("unchecked")
        Map<String, Object> propertyMap = (Map<String, Object>) request.get("propertyMap");
        String updatedBy = (String) request.get("updatedBy");
        String reason = (String) request.get("reason");
        Boolean effectiveImmediately = (Boolean) request.getOrDefault("effectiveImmediately", true);

        Agent agent = agentService.updateControlConfig(
            agentId,
            propertyMap,
            updatedBy,
            reason,
            effectiveImmediately
        );

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("agentId", agent.getAgentId());
        response.put("controlConfig", agent.getControlConfig());

        return ResponseEntity.ok(response);
    }

    /**
     * 获取控制配置
     * GET /api/agents/:agentId/control-config
     */
    @Operation(
        summary = "获取控制配置",
        description = "获取Agent的当前控制配置",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取配置"),
            @ApiResponse(responseCode = "404", description = "Agent不存在")
        }
    )
    @GetMapping("/agents/{agentId}/control-config")
    public ResponseEntity<Map<String, Object>> getControlConfig(
        @Parameter(description = "Agent ID", required = true) @PathVariable String agentId
    ) {
        Agent agent = agentService.getAgent(agentId);
        return ResponseEntity.ok(agent.getControlConfig());
    }

    /**
     * 健康检查
     * GET /api/health
     */
    @Operation(
        summary = "业务API健康检查",
        description = "检查业务API服务是否正常运行",
        responses = {
            @ApiResponse(responseCode = "200", description = "服务正常")
        }
    )
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> health() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "ok");
        response.put("service", "agent-platform-business-api");
        return ResponseEntity.ok(response);
    }

    /**
     * 系统指标
     * GET /api/metrics
     */
    @Operation(
        summary = "获取系统指标",
        description = "获取系统运行指标信息",
        responses = {
            @ApiResponse(responseCode = "200", description = "成功获取指标")
        }
    )
    @GetMapping("/metrics")
    public ResponseEntity<Map<String, Object>> metrics() {
        Map<String, Object> response = new HashMap<>();
        response.put("service", "agent-platform");
        response.put("uptime", System.currentTimeMillis());
        return ResponseEntity.ok(response);
    }
}
